package com.bw.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bw.home.adpter.HomePageAdapter
import com.bw.home.databinding.FragmentHomeBinding
import com.bw.home.intent.SimpleTypeIntent
import com.bw.home.entity.SimpleTypeEntity
import com.bw.home.state.SimpleTypeState
import com.bw.home.viewmodel.SimpleTypeViewModel
import com.bw.lib_mvi.view.BaseMVIFragment
import kotlinx.coroutines.launch

class HomeFragment : BaseMVIFragment() {
    lateinit var binding: FragmentHomeBinding
    lateinit var viewmodel: SimpleTypeViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun generateViewModel() {
        viewmodel = ViewModelProvider(this).get(SimpleTypeViewModel::class.java)
        loadSimpleType()
    }

    private fun loadSimpleType() {
        lifecycleScope.launch {
            viewmodel.intents.send(SimpleTypeIntent.getSimpleType)
        }
    }

    override fun handlerState() {
        lifecycleScope.launch {
            viewmodel.state.collect {
                when (it) {

                    is SimpleTypeState.SimpleTypeSuccess -> {
                        generateTab(it.data)
                    }

                    is SimpleTypeState.Failed -> {

                    }

                    else -> {}
                }
            }
        }

    }

    private fun generateTab(it: List<SimpleTypeEntity>) {
        val adapter = it?.let { HomePageAdapter(it, this.childFragmentManager) }
        binding.homeVp.adapter = adapter
        binding.homeTab.setupWithViewPager(binding.homeVp)
        binding.homeVp.adapter?.notifyDataSetChanged()
    }
}












